<?php
/*
 * User Management
 *
 */
class Controller_Admin_User extends Controller_Template 
{
	public function __construct($request, $response)
	{
		$this->_limit	= 2000;
		$this->template = 'admin/user/default';

		parent::__construct($request, $response);
	}

    public function action_list ($utype = 'merchant', $page = 1)
    {
        $offset = $this->_limit * (max(1, $page) - 1);
        $query  = array(
            'site'     => $utype,
            'order_by' => array('create_time' => 'DESC'),
        );
        $query  = $this->limit_auditor($query);
        $users  = User::search($query, $offset, $this->_limit);

        $this->template->set_filename("smarty:admin/user/list/$utype");
        $this->template->set('users', $users);
        $this->template->set('pagination', $this->pagination($users['count'], $this->_limit, 'route', 4));
    }

    public function action_detail ($utype = 'merchant', $uid)
    {
        $this->template->set_filename("smarty:admin/user/detail/$utype");
        $this->template->set('user', user::instance($uid)->get_user_info());
    }

    public function action_verify ($utype = 'merchant', $uid)
    {
        if ($utype == 'merchant')
        {
            $user = user::instance($uid)->upgrade_to_merchant();
            $this->request->redirect('/user/list/merchant');
        }
    }

    public function action_add ($utype = 'manager')
    {
        if ($utype == 'manager')
        {
            $post = $this->request->post();
            if (! empty($post))
            {
                try {
                $role_name = trim(Arr::get($post, 'role'));
                $user_info = array(
                    'passport' => trim(Arr::get($post, 'passport')),
                    'password' => trim(Arr::get($post, 'password')),
                    'mobile'   => trim(Arr::get($post, 'mobile')),
                    'nickname' => trim(Arr::get($post, 'nickname')),
                    'realname' => trim(Arr::get($post, 'realname')),
                );

                $status = 'activated';
                $utype  = 'manager';
                $uid    = user::create($user_info, $status, $utype);

                if ($uid > 0 && !empty($role_name))
                    user::instance($uid)->set_user_role ($role_name);

                $this->request->redirect('/user/detail/manager/'.$uid);
                return;

                }
                catch (Exception $e)
                {
                    $this->template->set('alert_message', $e->getMessage());
                }
            }

            $this->template->set_filename('smarty:admin/user/add/manager');
        }
    }

	public function action_index ()
	{
		// do nothing
		// this will show the default template page
		// 测试开始

		$roles					= User_Role_RoleDefine::get_all_names();

		$role_info	= '';
		$k			= 0;
		for($i=0;$i< count($roles);$i++)
		{
			
			if($roles[$i]['id'] != 1 && $roles[$i]['id'] != 1000)
			{	
				$role_info[$k] = $roles[$i];
				$k++;
			}
			
		}
		$function_name  = $this->request->controller();

		$this->template->set('roles',$role_info);
		$this->template->set('page_title', '新增管理员');
		$this->template->set('function_name', $function_name);	
		$this->template->set_filename('smarty:admin/user/addadmin');
	}

	public function action_add_admin()
	{
		$data	= '';
		if($this->request->post('action'))
		{
			$data['passport']	= $this->request->post('login_name');
			$data['realname']	= $this->request->post('realname');
			$data['mobile']		= $this->request->post('mobile');
			$data['nickname']	= $this->request->post('realname');
			$utype				= 'manager';
			$role				= $this->request->post('role_name');

		}
		$urole	= new User_Role_Role();

		$uid	= '';
		if($this->request->post('action') == 'add')
		{
			$insertid	= User::create($data,0,$utype);
						
			$rs			= $urole->insert_user_role_by_id($insertid,$role);

			$uid		= $insertid;
		}else{
			
			$insertid	= $this->request->post('uid');
			
			$uid		= $insertid;

		    $rs			= $urole->update_user_role_by_roleid($insertid, $role);	
		}
	
		//加任务权限
		$user_role		= new Model_Dao_UserRole();

		$insertdata['uid']		= $uid;

		$insertdata['role_id']	= intval($this->request->post('task_priviliage'));

		if(intval($insertdata['role_id']) > 0)
			$urs				= $user_role->insertOneRow($insertdata);
		
		$url	= '/user/admin_list';
		$this->request->redirect($url, $code = 302);
	}

	protected function del_admin($arr_del)
	{
		if(!empty($arr_del)){

			$u_role	= new User_Role_Role();
			
			$rs		= $u_role->delete_user_role_by_uids($arr_del);
		}
		return true;
	}
	
	public function action_admin_list ()
	{
		
		if($this->request->post('action')){

			$uids	= $this->request->post();
			
			$arr_del = array();
			foreach($uids as $key => $value)
			{
				if(strpos($key,'u_') === 0)
				{
					$key = explode('_',$key);
					$arr_del[] = $key[1];
				}
			}

			$this->del_admin($arr_del);
			//exit;
		}
		
		$query['site'] = 'manager';
			
		$page	= (isset($_GET['page'])) ? intval($_GET['page']) : 1;
		
		$offset	= $this->_limit * ($page - 1);
		
		$datas	= User::search($query,$offset, $this->_limit);

		$data	= $datas['list'];
		$count	= $datas['count'];
		$rs_data= '';
		$sum	= 0;
		for($i=0; $i< count($data); $i++)
		{
			$uid	= $data[$i]['uid'];

			$r_info	= User_Role_Role::get_user_role_info($uid);

			if(!empty($r_info)){

				$data[$i]['role_name']	= $r_info[0]['description'];
				$rs_data[]				= $data[$i];
				$sum++;
			}
	    }		
		//print_r($data);
		$page_config	= array(
							'total_items'		=> $count,
							'items_per_page'	=> $this->_limit,
							);

		$pagination		= Pagination::factory($page_config);
		$function_name  = $this->request->controller();

		$this->template->set_filename('smarty:admin/user/admin_list');
		$this->template->set('page_title', '管理员列表');
		$this->template->set('total', $sum);
		$this->template->set('pagination', $pagination->render());
		$this->template->set('data', $rs_data);
		$this->template->set('function_name', $function_name);
		$this->response->body($this->template->render());
	}

	public function action_admin_data($uid)
	{
		$query['site'] = 'manager';
	
		$query['uid']  = intval($uid);
		
		$datas	= User::search($query,0,1000);

		$data	= $datas['list'];

		$u_data	= '';
		for($i=0; $i< count($data); $i++)
		{
			if($data[$i]['uid'] == $uid)
				$u_data	= $data[$i];
		}
		$r_info	= User_Role_Role::get_user_role_info($uid);

		$data[0]['role_name']	= $r_info[0]['description'];
		$roles					= User_Role_RoleDefine::get_all_names();
		$role_info	= '';
		$k			= 0;
		for($i=0;$i< count($roles);$i++)
		{
			
			if($roles[$i]['id'] != 1 && $roles[$i]['id'] != 1000)
			{	
				$role_info[$k] = $roles[$i];
				if($r_info[0]['id'] == $roles[$i]['id'])
					$role_info[$k]['flag'] = 1;
				else
					$role_info[$k]['flag'] = 0;

				$k++;
			}
			
		}
		$function_name  = $this->request->controller();

		$this->template->set('function_name', $function_name);
		$this->template->set_filename('smarty:admin/user/admin_data');
		$this->template->set('page_title', '修改管理员信息');
		$this->template->set('data', $u_data);
		$this->template->set('roles', $role_info);	
		$this->response->body($this->template->render());
	}

    private function limit_auditor ($query)
    {
        $role_id = user::current_user()->get_role_id();
        if ($role_id == 'auditor')
        {
            $search = array(
                'manager' => user::current_user_id(),
                'status'  => Kohana::config('tuiguang.activity_channel.status.verified'),
                'enable_search_count' => FALSE,
                'format_results'      => FALSE,
            );

            $result = Promotion::search($search, NULL, NULL);
            $ids    = array(-1);
            foreach ($result['list'] as $rs)
                $ids[] = $rs['merchant_id'];

            $query['uid'] = array_unique($ids);
            return $query;
        }
        else
            return $query;
    }
}
